<?php

##################################################
#
# Copyright (c) 2004-2008 Ron Miller, OIC Group, Inc.
#
# This file is part of Exponent
#
# Exponent is free software; you can redistribute
# it and/or modify it under the terms of the GNU
# General Public License as published by the Free
# Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# GPL: http://www.gnu.org/licenses/gpl.txt
#
##################################################


/* 
exponentMail is an integrator class, bringing the flexibility of SwiftMail into Exponent gracefully.

More docs to follow as I become more familiar with SwiftMail. :-)
*/
if (!defined('EXPONENT')) exit('');

if ( version_compare ( phpversion(), "5.2.0", ">=" ) ) {
	require_once(BASE.'subsystems/mail/Swift.php');

// Create the class.
class exponentMail extends Swift {
	
	private $log = null;
	private $errStack = null;
	public $to = null;
	public $from = SMTP_FROMADDRESS;
	private $message = null;
	private $precallfunction = null;
	private $precalldata = null;
	private $postcallfunction = null;
	private $postcalldata = null;
	
	function __construct($params = array()) {
		Swift_CacheFactory::setClassName("Swift_Cache_Disk");
		Swift_Cache_Disk::setSavePath(BASE."/tmp");
		// Set up the mailer method.  Won't be using this anytime soon but its nice to have.
		if (array_key_exists('method',$params)) {
			switch ($params['method']) {
				case "multi":
					require_once(BASE.'subsystems/mail/Swift/Connection/Multi.php');
					require_once(BASE.'subsystems/mail/Swift/Connection/SMTP.php');
					require_once(BASE.'subsystems/mail/Swift/Connection/NativeMail.php');
					require_once(BASE.'subsystems/mail/Swift/Connection/Sendmail.php');
				break;
				case "smtp":
					require_once(BASE.'subsystems/mail/Swift/Connection/SMTP.php');
					if (array_key_exists('connections', $params)) {
						if (is_array($params['connections'])) {
							$conn = new Swift_Connection_SMTP($params['connections']['host'], $params['connections']['port'], $params['connections']['option']);
						} else {
							$conn = new Swift_Connection_SMTP($params['connections']);
						}
					} else {
						$conn = new Swift_Connection_SMTP(SMTP_SERVER, SMTP_PORT);
						$conn->setUsername(SMTP_USERNAME);
						$conn->setpassword(SMTP_PASSWORD);
					}
				break;
				case "native":
					require_once(BASE.'subsystems/mail/Swift/Connection/NativeMail.php');
					if ( isset($params['connections']) && !is_array($params['connections']) && $params['connections'] != '' ) {
						// Allow custom mail parameters.
						$conn = new Swift_Connection_NativeMail($params['connections']);
					} else {
						// Use default Mail parameters.
						$conn = new Swift_Connection_NativeMail();
					}
				break;
				case "sendmail":
					require_once(BASE.'subsystems/mail/Swift/Connection/Sendmail.php');
					if ( isset($params['connections']) && !is_array($params['connections']) && $params['connections'] != '' ) {
						// Allow a custom sendmail command to be run.
						$conn = new Swift_Connection_Sendmail($params['connections']);
					} else {
						// Attempt to auto-detect.
						$conn = new Swift_Connection_Sendmail(Swift_Conection_Sendmail::AUTO_DETECT);
					}
				break;
				case "rotator":
					require_once(BASE.'subsystems/mail/Swift/Connection/Rotator.php');
					require_once(BASE.'subsystems/mail/Swift/Connection/SMTP.php');
					require_once(BASE.'subsystems/mail/Swift/Connection/NativeMail.php');
					require_once(BASE.'subsystems/mail/Swift/Connection/Sendmail.php');
					if ( is_array ($params['connections']) ) {
						$conn = new Swift_Connection_Rotator($params['connections']);
					} else {
						$this->errStack['Connection'] = '$params[\'connections\'] must be an array to use the connection rotator.';
						$this->__destruct();
					}
					
				break;
			}
			// Use our current config vars 
		} else if (SMTP_USE_PHP_MAIL) {
			require_once(BASE.'subsystems/mail/Swift/Connection/NativeMail.php');
			if ( isset($params['connections']) && !is_array($params['connections']) && $params['connections'] != '' ) {
				// Allow custom mail parameters.
				$conn = new Swift_Connection_NativeMail($params['connections']);
			} else {
				// Use default Mail parameters.
				$conn = new Swift_Connection_NativeMail();
			}
		} else {
			require_once(BASE.'subsystems/mail/Swift/Connection/SMTP.php');
			if (array_key_exists('connections', $params)) {
				if (is_array($params['connections'])) {
					$conn = new Swift_Connection_SMTP($params['connections']['host'], $params['connections']['port'], $params['connections']['option']);
				} else {
					$conn = new Swift_Connection_SMTP($params['connections']);
				}
			} else {
				$conn = new Swift_Connection_SMTP(SMTP_SERVER, SMTP_PORT);
				$conn->setUsername(SMTP_USERNAME);
				$conn->setpassword(SMTP_PASSWORD);
			}
		}
		parent::__construct($conn);
		$this->message = new Swift_Message();
		
		switch (DEVELOPMENT) {
			case 1:
				$this->log = Swift_LogContainer::getLog();
				$this->log->setLogLevel(1);
			break;
			case 2:
				$this->log = Swift_LogContainer::getLog();
				$this->log->setLogLevel(5);
			break;
		}

	}
	// End Constructor

	// quick send method
	public function quickSend($params=array()) {

		
		if (empty($params['to'])) {
			return false;
		}
		
        	$this->addTo($params['to']);
        	if ( !empty($params['from'])) {
                	if (ereg('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $params['from'])) {
                        	$this->from = $params['from'];
                	}
        	}
	
		if (!empty($params['subject'])) $this->subject($params['subject']);
	        if (!empty($params['headers'])) $this->addHeaders($params['headers']);
        	if (!empty($params['html_message'])) $this->addHTML($params['html_message']);
        	if (!empty($params['text_message'])) $this->addText($params['text_message']);
               	return $this->send();
	}	
    public function check_email($email)
  {
      global $db;
    //Jan 3, 2013 - sonhb - get_detail email 
      $email_detail=$db->selectObject("mailsystem_email","email='".$email."'");
      if($email_detail->block)
      return false;
      
      if(!$email_detail)
      {
          $email_detail->email=$email;
          $email_detail->date=time();
          mailsystemmodule::logMail('addemail',$email,"Add {$email} to list email");
          $db->insertObject($email_detail,'mailsystem_email'); 
          return $email;         
      }
      else
      {
          $email_detail->count=$email_detail->count+1;
          $email_detail->last_send=time();          
          $db->updateObject($email_detail,'mailsystem_email','id='.$email_detail->id);
      }
      return $email;
      //Jan 3, 2013 - sonhb - get_detail email - end
  }
  //Jan 3, 2013 - sonhb - createlog event
  public function logmail($email,$decription)
  {
      global $db;
      $log=null;
      $log->email=$email;
      $log->date=time();
      $log->description=$decription;
      $db->insertObject($log,'mailsystem_log');
      return true;
  }
  
  function insert_to_send($subject,$content,$mail_type,$file='',$email_to,Swift_Address $email_from,$group='All') {
      global $db;
        $mail=null;
        $mail->subject=$subject;//
        $mail->content=$content;
        $mail->mail_type=$mail_type;
        $mail->file=$file;
        $mail->mail_status=0;
        $mail->email_to=$email_to;
        //Email from
        $mail->email_from=$email_from->getAddress();
        $mail->email_from_name=$email_from->getName();
        $mail->date_insert=time();
        $mail->group=$group;
        $db->insertObject($mail,'mailsystem_mail');
        mailsystemmodule::logMail('insertmail',$mail->email_to,"Insert <{$mail->subject}> to queues");
        return true;
    }
	//Override the parent send function so we can set up the send to be cleaner.
	public function send () {        
		return parent::send($this->message, $this->to, $this->from);
	}
    

    //Jan 3,2013 - real send mail
    public function quick_send ($subject,$content,$mail_type,$file,$email, $email_from,$email_from_name,$group='All')
    {
         $email_from= new Swift_Address($email_from,$email_from_name);
         $check=$this->check_email($email);
            if($check)
            {                
        return $this->insert_to_send(
               $subject,
               $content,
               $mail_type,
               $file,
               $check,
               $email_from,
               $group);
    }
    }
    public function real_send ($subject, $content, $format=0, $receive=array(), $dont_add_admin=false,$from_mail,$from){
        global $db;
            $email_detail=$db->selectObject("mailsystem_email","email='".$receive."'");
            
            // send email to admin 
            $headers['From'] =  $from_mail ;
            $headers['Reply-to'] = $from_mail;
            
            if ($dont_add_admin==false)
                $this->addTo($from_mail);
            if (!is_array($receive))
            {
                $receive=array($receive);
            }
            foreach ($receive as $v)
                $this->addTo($v);

            $this->subject($subject);
            if ($format == 0)
                $this->addHTML($content);
            else
                $this->addText($content);
            $this->addHeaders($headers);
            $this->addFrom($from_mail, $from );
            try{
                @$this->send();
                $email_detail->count++;
                $email_detail->last_send=time();
                $db->updateObject($email_detail,'mailsystem_email','id='.$email_detail->id);
                return true;
            }
            catch (Exception $e){
                $email_detail->count_error++;
                
                $db->updateObject($email_detail,'mailsystem_email','id='.$email_detail->id);
                return false;
            }       
        
    }
	public function batchSend() {
		require_once(BASE.'subsystems/mail/Swift/Plugin/AntiFlood.php');
		$this->attachPlugin(new Swift_Plugin_AntiFlood(200, 5),"anti-flood");
		$batch = new Swift_BatchMailer($this);
		$batch->setSleepTime(1);
		$batch->setMaxTries(1);
		$batch->send($this->message, $this->to, $this->from);
		return $batch->getFailedRecipients();
	}
	
	public function addHeaders($headers) {
		foreach ($headers as $header=>$value) {
			$this->message->headers->set($header, $value);
		}
	}
    //Jan 3,2013 - change add function
	public function go_addHTML($html) {
        $this->message->temp_data->text=$html;
        $this->message->temp_data->type=0;
    }
    
    public function go_addText($text) {
        $this->message->temp_data->text=$text;
        $this->message->temp_data->type=1;
    }
    
    //Jan 3,2013 - change add function - end
    
    //Jan 3,2013 - real function change to go_***
	public function addHTML($html) {
		$this->message->attach(new Swift_Message_Part($html, "text/html"));
	}
	
	public function addText($text) {
		$this->message->attach(new Swift_Message_Part($text, "text/plain"));
	}
	
	public function addRaw($body) {
		$this->message->setBody($body);
	}
	//Jan 3,2013 - real function change to go_*** - end
	public function addTo ($a = '', $b = '') {
		if (!is_object($this->to)) {
			$this->to = new Swift_RecipientList();
		}
		if (is_array($a)) {
			foreach ($a as $addr) {
				$this->to->addTo($addr);
			}
		} else {
			if ($b != '') {
				$this->to->addTo($a, $b);
			} else {
				$this->to->addTo($a);
			}
		}	
	}
	
	public function addFrom($email=null, $name=null) {
	    if (!empty($email) && !empty($name)) {
	        $this->from = new Swift_Address($email, $name);
	    } else {
	        $this->from = $email;
	    }
	}
		
	public function messageId() {
		if (!is_object($this->message)) {
			$this->message = new Swift_Message();
		}
		return $this->message->generateId();
	}
	
	public function subject ($subj) { 
		if (!is_object($this->message)) {
			$this->message = new Swift_Message();
		}
		$this->message->headers->set("Subject", $subj);
	}
	
	public function clearBody () {
		$this->message->setBody("");
	}
	
	public function flushRecipients() {
	    $this->to->flush();
	}
	
	function __destruct() {
	/*
		if (DEVELOPMENT != 0) {
			eLog($this->log->dump(true));
		}
	*/
		if ($this->errStack != null) {
			eDebug($error);
		}
	}
}
// End Mail class.
// Pre-send processing class. (Incomplete)
/*
class preSend implements Swift_Events_BeforeSendListener {
	
	public function beforeSendPerformed(Swift_Events_SendEvent $e) {
		
	}
}
*/
} else {
	eDebug ("You must be using PHP 5.2 or greater to use the exponent mail subsystem.");
}
?>
